package com.ehome.poct.core.utils;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ArrayUtil;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.ValidationException;
import javax.validation.Validator;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @auther: kuiba.peng
 * @date: 2022/10/28 14:25
 * @description:
 */
public class ValidateUtil {

    private static final Validator VALIDATOR = Validation.buildDefaultValidatorFactory().getValidator();

    /**
     * 校验实体类
     */
    public static <T> void validate(T t) {
        Set<ConstraintViolation<T>> constraintViolations = VALIDATOR.validate(t);
        if (constraintViolations.size() == 0) {
            return;
        }
        String errorMsg = constraintViolations.stream().map(ConstraintViolation::getMessage).collect(Collectors.joining(";"));
        throw new ValidationException(errorMsg);
    }

    /**
     * 通过组来校验实体类
     */
    public static <T> void validate(T t, Class<?>... groups) {
        Set<ConstraintViolation<T>> constraintViolations;
        if (ArrayUtil.isEmpty(groups)) {
            validate(t);
            return;
        } else {
            constraintViolations = VALIDATOR.validate(t, groups);
        }
        if (CollUtil.isEmpty(constraintViolations)) {
            return;
        }
        String errorMsg = constraintViolations.stream().map(ConstraintViolation::getMessage).collect(Collectors.joining(";"));
        throw new ValidationException(errorMsg);
    }
}
